<template>
  <div
    v-loading="allLoading"
    class="order-create-form-wrapper"
    element-loading-text="加载中..."
    @click="visibleSearch ? (visibleSearch = false) : ''"
  >
    <div class="order-create-form-container">
      <!-- 创建工单 -->
      <div class="header">
        <h4 class="title">新建工单</h4>
        <div class="btn_group">
          <h-plain-button @click="submitOrder">提交</h-plain-button>
          <h-button @click="onCancelOrder">取消</h-button>
        </div>
      </div>

      <div class="divider"></div>

      <div class="all_form_container">
        <!-- 公司信息 -->
        <div ref="customerInfoDiv" class="customer_info">
          <div class="title">公司信息</div>
          <el-form
            ref="customerInfoFormInstance"
            :model="basicData"
            :rules="rules"
            label-position="top"
            inline-message
          >
            <div class="form_content">
              <!--地址识别-->
              <!-- <div class="form_item_container">
                <el-form-item label="地址识别">
                  <div class="address_identify">
                    <el-input
                      v-model.trim="allUserInfo"
                      maxlength="300"
                      show-word-limit
                      placeholder="粘贴整段信息到此文本框如：张三，15815151515，北京市市辖区石景山区中山路25号"
                      type="textarea"
                      resize="both"
                    />
                    <HButton type="primary" :loading="addrParseLoading" @click="onAddrParse"
                      >识别</HButton
                    >
                  </div>
                </el-form-item>
              </div> -->

              <!--客户名称、客户电话-->
              <el-form-item label="客户名称" prop="name" class="top">
                <el-popover :visible="companyNameSelectPopoverVisible" :width="370">
                  <template #reference>
                    <el-input
                      v-model.trim="basicData.name"
                      placeholder="请输入客户名称"
                      clearable
                      @clear="onClearUserInfo"
                      @input="handleCompanyNameInput"
                      @blur="companyNameSelectPopoverVisible = false"
                    />
                  </template>

                  <el-table
                    v-loading="getUserOptionsLoading"
                    :max-height="300"
                    :border="true"
                    :data="userOptions"
                    @row-click="handleCompanySelect"
                  >
                    <!-- 序号 -->
                    <el-table-column label="序号" type="index" :width="50" />

                    <!-- 客户名称 -->
                    <el-table-column
                      label="客户名称"
                      :min-width="100"
                      show-overflow-tooltip
                      prop="name"
                    />

                    <!-- 客户电话 -->
                    <el-table-column
                      label="客户电话"
                      :width="120"
                      show-overflow-tooltip
                      prop="phone"
                    />
                  </el-table>
                </el-popover>
              </el-form-item>
              <el-form-item label="报单公司" prop="repairCompany" class="top">
                <el-popover :visible="sendRepairUserSelectPopoverVisible" :width="370">
                  <template #reference>
                    <el-input
                      v-model.trim="basicData.repairCompany"
                      placeholder="请输入报单公司"
                      clearable
                      @clear="onClearSendRepairUserInfo"
                      @input="handleSendRepairUserInput"
                      @blur="sendRepairUserSelectPopoverVisible = false"
                    />
                  </template>

                  <el-table
                    v-loading="getSendRepairUserOptionListLoading"
                    :max-height="300"
                    :border="true"
                    :data="sendRepairUserOptionList"
                    @row-click="handleSendRepairUserChange"
                  >
                    <!-- 序号 -->
                    <el-table-column label="序号" type="index" :width="50" />

                    <!-- 报单公司名称 -->
                    <el-table-column
                      label="报单公司名称"
                      :min-width="100"
                      show-overflow-tooltip
                      prop="name"
                    />

                    <!-- 报单公司电话 -->
                    <el-table-column
                      label="报单公司电话"
                      :width="120"
                      show-overflow-tooltip
                      prop="phone"
                    />
                  </el-table>
                </el-popover>
              </el-form-item>

              <el-form-item label="收件人">
                <el-input v-model.trim="basicData.addressee" placeholder="请输入收件人" />
              </el-form-item>

              <!-- 客户电话 -->
              <el-form-item class="customer_phone top" label="客户电话" prop="phone">
                <el-input
                  v-model.trim.number="basicData.phone"
                  maxlength="11"
                  placeholder="请输入客户电话"
                />
              </el-form-item>

              <!-- 报单公司电话 -->
              <el-form-item
                class="customer_phone top"
                label="报单公司电话"
                prop="repairCompanyPhone"
              >
                <el-input
                  v-model.trim.number="basicData.repairCompanyPhone"
                  maxlength="11"
                  placeholder="请输入报单公司电话"
                />
              </el-form-item>

              <el-form-item label="收件人电话">
                <el-input
                  v-model.trim.number="basicData.addresseePhone"
                  maxlength="11"
                  placeholder="请输入收件人电话"
                />
              </el-form-item>

              <!-- 报单人信息 -->
              <el-form-item
                class="customer_send top"
                label="报单人信息"
                prop="sendForRepairUsername"
              >
                <el-input
                  v-model.trim="basicData.sendForRepairUsername"
                  placeholder="请输入报单人信息"
                />
              </el-form-item>

              <el-form-item label="项目名称">
                <el-input v-model.trim="basicData.project" placeholder="请输入项目名称" />
              </el-form-item>

              <el-form-item label="收件地址">
                <el-input
                  v-model.trim="basicData.address"
                  type="textarea"
                  placeholder="请输入收件地址"
                  maxlength="200"
                  show-word-limit
                  resize="both"
                />
              </el-form-item>

              <!-- 报单人电话 -->
              <el-form-item class="customer_send top" label="报单人电话" prop="sendForRepairPhone">
                <el-input
                  v-model.trim.number="basicData.sendForRepairPhone"
                  placeholder="请输入报单人电话"
                  maxlength="11"
                />
              </el-form-item>

              <!--公司地址、详细地址-->
              <!-- <el-form-item class="customer_address top" label="公司地址" prop="customerAddress">
                  <SingleAddress ref="singleAddressRef" :address="addrs" />
                </el-form-item>
                <el-form-item class="top" label="详细地址" prop="address">
                  <el-input
                    v-model.trim="basicData.address"
                    maxlength="200"
                    placeholder="请输入详细地址"
                    show-word-limit
                    type="textarea"
                    resize="both"
                    class="detail_address"
                  />
                </el-form-item> -->

              <!-- 报单人电话 -->
              <!-- <el-form-item class="customer_send" label="报单人电话" prop="sendForRepairPhone">
                <el-input
                  v-model.trim.number="basicData.sendForRepairPhone"
                  maxlength="11"
                  placeholder="请输入报单人电话"
                />
              </el-form-item> -->

              <!-- 是否为工作日 -->
              <!-- <el-form-item class="is-work-day" label="是否为工作日" prop="isWorkDay">
                <el-switch v-model="basicData.isWorkDay" size="small" />
              </el-form-item> -->
            </div>
          </el-form>
        </div>

        <!-- 工单信息 -->
        <div ref="basicInfoDiv" class="order_info">
          <div class="title">工单信息</div>
          <el-form
            ref="basicInfoFormInstance"
            :model="basicData"
            :rules="rules"
            label-position="top"
            inline-message
          >
            <!-- 工单类型 -->
            <el-form-item label="工单类型" prop="moduleId">
              <el-select
                v-model="basicData.moduleId"
                :loading="loading"
                :filter-method="handleGetOrderTypeOptions"
                clearable
                filterable
                placeholder="工单类型"
                remote-show-suffix
                @clear="type = ''"
              >
                <el-option
                  v-for="(item, index) in modules"
                  :key="index"
                  :disabled="item.disabled"
                  :label="item.name"
                  :value="item.id"
                  @click="handleChangeModule(item)"
                />
              </el-select>
            </el-form-item>

            <!-- 工单来源 -->
            <el-form-item label="工单来源" prop="source">
              <el-select
                v-model="basicData.workSourceId"
                placeholder="工单来源"
                filterable
                :loading="getSourceOptionListLoading"
                :filter-method="handleGetSourceOptionList"
              >
                <el-option
                  v-for="(item, index) in sourceOptionList.filter((item) => !item.disabled)"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>

            <!-- 报单时间 -->
            <el-form-item label="报单时间">
              <el-date-picker
                v-model="now"
                :default-value="new Date()"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm"
              />
            </el-form-item>

            <!-- 分派部门 -->
            <el-form-item label="分派部门">
              <el-select
                v-model="network"
                :loading="getNetworkOptionsLoading"
                :filter-method="getNetworkPageSelectList"
                clearable
                filterable
                placeholder="分派部门"
                remote-show-suffix
                :disabled="userStore.isCurrentRoleNetwork && !!loginedAccountNetwork"
              >
                <!-- <el-option :value="0" label="按规则分配">
                  <div style="display: flex; justify-content: space-between; align-items: center">
                    <span>按规则分配</span> <span style="color: #fb9337">系统</span>
                  </div>
                </el-option> -->
                <el-option
                  v-for="item in networks"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>

            <!-- 工单分类 -->
            <!-- <el-form-item label="工单分类">
              <el-cascader
                v-model="type"
                :before-filter="inputChangeType"
                :options="types"
                :props="CascaderProps"
                clearable
                filterable
                placeholder="工单分类"
                @visible-change="changeType"
              />
            </el-form-item> -->

            <!-- 受理客服 -->
            <!-- <el-form-item label="受理客服">
              <el-select
                v-model="customer"
                :loading="loading"
                :filter-method="getworkTeamPageSelect"
                clearable
                filterable
                placeholder="受理客服"
                remote-show-suffix
              >
                <el-option :value="0" label="按规则分配">
                  <div style="display: flex; justify-content: space-between; align-items: center">
                    <span>按规则分配</span> <span style="color: #fb9337">系统</span>
                  </div>
                </el-option>
                <el-option
                  v-for="item in customers"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item> -->

            <!-- 处理方式 -->
            <!-- <el-form-item label="处理方式">
              <el-cascader
                v-model="method"
                :before-filter="inputChangeMethod"
                :options="methodss"
                :props="CascaderProps"
                clearable
                filterable
                placeholder="处理方式"
                @visible-change="changeMmethod"
              />
            </el-form-item> -->

            <!-- <template v-if="type === 2"> -->
            <!-- 处理类型 -->
            <el-form-item label="处理类型">
              <el-select
                :model-value="basicData.faultTypeRelationVos.map((item) => item.oneFaultTypeId)"
                :loading="getFaultTypesLoading"
                placeholder="处理类型"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                @change="handleFaultTypeSelect"
                @remove-tag="handleRemoveFaultType"
              >
                <el-option
                  v-for="(faultType, faultTypeIndex) in faultTypes"
                  :key="faultTypeIndex"
                  :value="faultType.id"
                  :label="faultType.name"
                />
              </el-select>
            </el-form-item>

            <!-- 分类 -->
            <el-form-item label="分类">
              <el-select
                :model-value="basicData.faultRelationVos.map((item) => item.faultId)"
                :loading="getFaultByTypeLoading"
                placeholder="分类"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="2"
                allow-create
                filterable
                :no-data-text="
                  basicData.faultTypeRelationVos.map((item) => item.oneFaultTypeId).length === 0
                    ? '请选择处理类型'
                    : '无数据'
                "
                @change="handleFaultPhenomenonChange"
                @remove-tag="handleFaultPhenomenonRemove"
              >
                <el-option
                  v-for="(fault, faultIndex) in faultList"
                  :key="faultIndex"
                  :value="fault.id"
                  :label="`${fault.code} ${fault.name}`"
                  :disabled="fault.disabled"
                >
                  <div class="fault-phenomenon-option">
                    <div style="margin-right: 20px">
                      <h-tooltip-text
                        :text="fault.code"
                        :max-width="60"
                        :height="36"
                        text-align="right"
                      />
                    </div>
                    <div>
                      <h-tooltip-text :text="fault.name" :max-width="320" :height="36" />
                    </div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <!-- </template> -->

            <!-- <template v-if="type === 2"> -->
            <!-- 详情 -->
            <el-form-item label="详情">
              <el-select
                v-if="faultReasonOptions.length"
                :model-value="basicData.faultReason.map((item) => item.id)"
                placeholder="请选择详情"
                allow-create
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                filterable
                default-first-option
                :reserve-keyword="false"
                @change="handleFaultReasonSelect"
              >
                <el-option
                  v-for="(reason, reasonIndex) in faultReasonOptions"
                  :key="reasonIndex"
                  :label="reason.content"
                  :value="reason.id"
                >
                  <h-tooltip-text :text="reason.content" :max-width="150" :height="32" />
                </el-option>
              </el-select>
              <el-input
                v-else
                v-model.trim="basicData.faultReason"
                placeholder="请输入详情"
                show-word-limit
                type="textarea"
                resize="both"
                class="desc-28-height"
              />
            </el-form-item>

            <!-- 解决措施/维修方案 -->
            <el-form-item label="解决措施/维修方案">
              <el-select
                v-if="solveOptions.length"
                :model-value="basicData.solution.map((item) => item.id)"
                placeholder="请选择解决措施/维修方案"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                filterable
                allow-create
                default-first-option
                :reserve-keyword="false"
                @change="handleSolveSelect"
              >
                <el-option
                  v-for="(solve, solveIndex) in solveOptions"
                  :key="solveIndex"
                  :label="solve.content"
                  :value="solve.id"
                >
                  <h-tooltip-text
                    :text="solve.content"
                    :max-width="300"
                    :height="32"
                  ></h-tooltip-text>
                </el-option>
              </el-select>
              <el-input
                v-else
                v-model.trim="basicData.solution"
                placeholder="请输入解决措施/维修方案"
                show-word-limit
                type="textarea"
                resize="both"
                class="desc-28-height"
              />
            </el-form-item>
            <!-- </template> -->

            <!-- 服务级别 -->
            <!-- <el-form-item label="服务级别">
              <el-select
                v-model="grade"
                placeholder="服务级别"
                :loading="loading"
                :filter-method="getworkLevelPageSelect"
                clearable
                filterable
                remote-show-suffix
              >
                <el-option
                  v-for="item in grades"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item> -->

            <!-- 故障现象描述 -->
            <el-form-item label="故障现象描述" prop="content">
              <div class="fault-desc-container">
                <el-input
                  v-model.trim="basicData.content"
                  maxlength="200"
                  placeholder="请输入故障现象描述"
                  show-word-limit
                  type="textarea"
                  resize="both"
                  :class="'desc-28-height'"
                />
                <!-- <div class="quick-item-list">
                  <template v-for="quickItem in descQuickFillList" :key="quickItem">
                    <div
                      v-if="!basicData.content.includes(quickItem)"
                      class="quick-item"
                      @click="handleDescQuickFillItemClick(quickItem)"
                      >{{ quickItem }}</div
                    >
                  </template>
                </div> -->
              </div>
            </el-form-item>

            <el-form-item label="服务日期">
              <el-date-picker
                v-model="basicData.serviceDate"
                type="date"
                placeholder="请选择服务日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>

            <!-- 工单图片 -->
            <el-form-item label="工单图片（最多只能上传10张）">
              <div class="upload_file_container">
                <div v-for="(item, index) in fileList" :key="index">
                  <h-image
                    :preview-src-list="fileList.map((file) => file.image)"
                    :src="item.image"
                    :initial-index="index"
                    :width="80"
                    :height="50"
                    :padding="2"
                    @del="handleDelOrderPicture(index)"
                  />
                  <div class="file_name">
                    <h-tooltip-text :text="item.name" :max-width="80" :height="16" />
                  </div>
                </div>
                <div v-if="fileList.length < 10">
                  <el-upload
                    v-model="fileList"
                    class="order-picture-upload"
                    :auto-upload="false"
                    :on-change="handleUploadOrderPicture"
                    :show-file-list="false"
                    accept="image/*"
                    action="#"
                    drag
                    multiple
                  >
                    <el-icon :size="24" color="#007cff">
                      <UploadFilled />
                    </el-icon>
                  </el-upload>
                </div>
              </div>
            </el-form-item>

            <div style="display: flex; column-gap: 72px">
              <el-form-item label="设备故障图">
                <div class="upload_file_container">
                  <h-image
                    v-if="goodFaultImgFile.url"
                    :src="goodFaultImgFile.url"
                    :width="80"
                    :height="50"
                    :padding="2"
                    @del="onDelGoodFaultImgFile"
                  />
                  <el-upload
                    v-else
                    v-model="goodFaultImgFile.file"
                    :limit="1"
                    class="order-picture-upload"
                    :auto-upload="false"
                    :on-change="handleUploadGoodFaultImg"
                    :show-file-list="false"
                    accept="image/*"
                    action="#"
                    drag
                  >
                    <el-icon :size="24" color="#007cff">
                      <UploadFilled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>

              <el-form-item label="设备序列号图">
                <div class="upload_file_container">
                  <h-image
                    v-if="goodCodeImgFile.url"
                    :src="goodCodeImgFile.url"
                    :width="80"
                    :height="50"
                    :padding="2"
                    @del="onDelGoodSnCodeImgFile"
                  />
                  <el-upload
                    v-else
                    v-model="goodCodeImgFile.file"
                    :limit="1"
                    class="order-picture-upload"
                    :auto-upload="false"
                    :on-change="handleUploadGoodCodeImg"
                    :show-file-list="false"
                    accept="image/*"
                    action="#"
                    drag
                  >
                    <el-icon :size="24" color="#007cff">
                      <UploadFilled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- 自定义信息 -->
        <div v-if="customFieldList.length > 0" ref="customInfoDiv" class="custom_info">
          <div class="title">工单维修信息</div>
          <div class="form-content">
            <el-form
              v-for="(field, index) in customFieldList.filter((item) =>
                [1, 3, 4, 8, 9, 10].includes(item.type),
              )"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="field.name"
                :prop="field.type === 4 ? 'valList' : 'val'"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请输入内容',
                    trigger: ['change', 'blur'],
                  },
                ]"
              >
                <!-- 单行文本 -->
                <el-input
                  v-if="field.type === 1"
                  v-model.trim="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请输入内容'"
                  maxlength="100"
                />

                <!-- 单选 -->
                <el-select
                  v-if="field.type === 3"
                  v-model="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请选择'"
                >
                  <el-option
                    v-for="(option, optionIndex) in field.contents"
                    :key="optionIndex"
                    :label="option.val"
                    :value="option.val"
                  ></el-option>
                </el-select>

                <!-- 多选 -->
                <el-select
                  v-if="field.type === 4"
                  v-model="customFieldList[field.formCustomFieldIndex].valList"
                  :placeholder="field.tip || '请选择'"
                  multiple
                >
                  <el-option
                    v-for="(option, optionIndex) in field.contents"
                    :key="optionIndex"
                    :label="option.val"
                    :value="option.val"
                  />
                </el-select>

                <!-- 评分 -->
                <el-rate
                  v-if="field.type === 8"
                  :model-value="Number(customFieldList[field.formCustomFieldIndex].val) / 2"
                  @change="(val: number) => customFieldList[field.formCustomFieldIndex].val = String(val * 2)"
                />

                <!-- 日期 -->
                <el-date-picker
                  v-if="field.type === 9"
                  v-model="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请选择日期'"
                  @change="handleChangeDate(field.formCustomFieldIndex)"
                />

                <!-- 日期时间 -->
                <el-date-picker
                  v-if="field.type === 10"
                  v-model="customFieldList[field.formCustomFieldIndex].val"
                  type="datetime"
                  format="YYYY-MM-DD HH:mm"
                  date-format="MMM DD, YYYY"
                  time-format="HH:mm"
                  :placeholder="field.tip || '请选择日期时间'"
                  @change="handleChangeDateTime(field.formCustomFieldIndex)"
                />
              </el-form-item>
            </el-form>

            <!-- 图片上传 -->
            <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 5)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="`${field.name}（最多上传${field.uploadQty}张）`"
                prop="fileList"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传图片',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <div class="custom-field-upload">
                  <div v-for="(img, imgIndex) in field.fileList" :key="imgIndex" class="file">
                    <h-image
                      :width="80"
                      :height="50"
                      :initial-index="imgIndex"
                      :preview-src-list="field.fileList.map((item) => item.url)"
                      :padding="2"
                      :src="img.url"
                      @del="handleDelFile(field.formCustomFieldIndex, imgIndex)"
                    />
                    <h-tooltip-text :text="img.file.name" :max-width="80" :height="16" />
                  </div>
                  <el-upload
                    v-if="field.fileList.length < field.uploadQty"
                    class="upload-picture upload-wrapper"
                    multiple
                    accept="image/*"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => handleUploadFile(file, field.formCustomFieldIndex)"
                  >
                    <el-icon :size="24" color="#007cff">
                      <upload-filled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
            </el-form>

            <!-- 附件上传 -->
            <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 6)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="`${field.name}（最多上传${field.uploadQty}个）`"
                prop="fileList"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传附件',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <div class="custom-field-upload">
                  <div v-for="(pdf, pdfIndex) in field.fileList" :key="pdfIndex" class="file">
                    <h-image
                      :width="80"
                      :height="50"
                      :initial-index="pdfIndex"
                      :is-show-img-preview="false"
                      :padding="2"
                      :src="pdfPlaceholderImg"
                      @preview="
                        handlePdfPreview(
                          field.fileList.map((item) => item.url),
                          pdfIndex,
                        )
                      "
                      @del="handleDelFile(field.formCustomFieldIndex, pdfIndex)"
                    />
                    <h-tooltip-text :text="pdf.file.name" :max-width="80" :height="16" />
                  </div>
                  <el-upload
                    v-if="field.fileList.length < field.uploadQty"
                    class="upload-pdf upload-wrapper"
                    multiple
                    accept=".pdf"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => handleUploadFile(file, field.formCustomFieldIndex)"
                  >
                    <el-icon :size="24" color="#007cff">
                      <upload-filled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
            </el-form>

            <!-- 视频上传 -->
            <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 7)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="`${field.name}（最多上传${field.uploadQty}个）`"
                prop="fileList"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传视频',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <div class="custom-field-upload">
                  <div v-for="(video, videoIndex) in field.fileList" :key="videoIndex" class="file">
                    <h-image
                      :width="80"
                      :height="50"
                      :initial-index="videoIndex"
                      :is-show-img-preview="false"
                      :padding="2"
                      :src="videoPlaceholderImg"
                      @preview="
                        handleVideoPreview(
                          field.fileList.map((item) => item.url),
                          videoIndex,
                        )
                      "
                      @del="handleDelFile(field.formCustomFieldIndex, videoIndex)"
                    />
                    <h-tooltip-text :text="video.file.name" :max-width="80" :height="16" />
                  </div>
                  <el-upload
                    v-if="field.fileList.length < field.uploadQty"
                    class="upload-video upload-wrapper"
                    multiple
                    accept="video/*"
                    :auto-upload="false"
                    :show-file-list="false"
                    :on-change="(file: UploadFile) => handleUploadFile(file, field.formCustomFieldIndex)"
                  >
                    <el-icon :size="24" color="#007cff">
                      <upload-filled />
                    </el-icon>
                  </el-upload>
                </div>
              </el-form-item>
            </el-form>

            <!-- 多行文本 -->
            <el-form
              v-for="(field, index) in customFieldList.filter((item) => item.type === 2)"
              ref="customFieldFormInstance"
              :key="index"
              :model="customFieldList[field.formCustomFieldIndex]"
              label-position="top"
              inline-message
            >
              <el-form-item
                :label="field.name"
                prop="val"
                :rules="[
                  {
                    required: field.required,
                    message: field.tip || '请上传视频',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <el-input
                  v-model.trim="customFieldList[field.formCustomFieldIndex].val"
                  :placeholder="field.tip || '请输入'"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  resize="both"
                />
              </el-form-item>
            </el-form>
          </div>
        </div>

        <div ref="goodInfoDiv" class="good-info">
          <good-info
            ref="goodInfoInstance"
            :factory-id="String(network) || ''"
            :user-id="basicData.userId"
            @change-goods="changeGoods()"
            @change-user="handleGoodInfoChangeUser"
          />
        </div>

        <!-- 文件查看 -->
        <h-dialog v-model="dialogContract" title="查看附件" :width="900">
          <iframe :src="`${file}`" frameborder="0" height="600" width="100%"></iframe>
        </h-dialog>

        <!-- 创建公司 -->
        <el-dialog v-model="createUserDialogVisit" :draggable="true" title="创建公司" width="400px">
          <el-form
            ref="createUserRef"
            :model="createUserForm"
            :rules="createUserFormRules"
            label-position="left"
            label-width="90px"
          >
            <el-form-item label="客户名称" prop="name">
              <el-input v-model.trim="createUserForm.name" clearable placeholder="请输入客户名称" />
            </el-form-item>
            <el-form-item label="客户电话" prop="phone">
              <el-input
                v-model.trim="createUserForm.phone"
                clearable
                maxlength="11"
                placeholder="请输入客户电话"
                @input="createUserForm.phone = createUserForm.phone.replace(/[^0-9]/g, '')"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="createUserDialogVisit = false">取消</el-button>
              <el-button class="btn-bg2" @click="onSaveCreateUser(createUserRef)">保存</el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>

    <video-preview
      v-model:visible="videoPreviewModalVisible"
      :video-list="videoPreviewUrls"
      :initial-index="videoPreviewInitialIndex"
    />

    <pdf-preview
      v-model:visible="pdfPreviewModalVisible"
      :initial-index="pdfPreviewInitialIndex"
      :pdf-list="pdfPreviewUrls"
    />
  </div>
</template>

<script lang="ts" setup>
  import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
  import { UploadFilled } from '@element-plus/icons-vue'
  import pdfPlaceholderImg from '@/assets/image/pdf.png'
  import type { FormInstance, FormRules, UploadFile, UploadRawFile } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import { useRoute, useRouter } from 'vue-router'
  import {
    addSave,
    getModuleField,
    getUserSelect,
    workLevelPageSelect,
    workModulePageSelect,
    workModuleTypePageSelect,
    workModuleWayPageSelect,
  } from '@/api/order'
  import { getLoginAccountNetworkId, getNetworkPageSelect } from '@/api/network'
  import { empPageSelecct } from '@/api/organize'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { orderAnnexUpload, orderVideoUpload } from '@/api/upload'
  import { useSettingStore } from '@/store/modules/setting'
  import { useTagsViewStore } from '@/store/modules/tagsView'
  import _ from 'lodash'
  import { CustomField, Form, OrderType } from './types'
  // import useAddrParseService from '@/views/order/new/services/useAddrParseService'
  import useRepeatOrder from '@/views/order/new/services/useRepeatOrder'
  import videoPlaceholderImg from '@/assets/image/pages/order/new/video.png'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import GoodInfo from '@/components/pages/order/create/good-info/index.vue'
  import { markRaw } from 'vue'
  import { WarningFilled, CircleCloseFilled } from '@element-plus/icons-vue'
  import { ElMessageBox, ElIcon } from 'element-plus'
  import routeComponentName from '@/config/route-component-name'
  // import moment from 'moment'
  import { useGetFaultTypes } from '@/services/pages/know/fault/useFaultType'
  // import { useGetFaultByType } from '@/services/pages/know/useFault'
  import { getFaultByType } from '@/api/knowledge'
  import VideoPreview from '@/components/pages/return-factory/index/create/custom-info/VideoPreview.vue'
  import PdfPreview from '@/components/pages/return-factory/index/create/custom-info/PdfPreview.vue'
  import { useGetSourceOptionList } from '@/services/pages/order/useSoruce'
  import {
    useGetUserCreditLimit,
    useGetMainContactPersonOptionList,
  } from '@/services/pages/user/useUser'
  import { useUserStore } from '@/store/modules/user'
  import { verifyPhone } from '@/utils/validate'
  import { TableDataGoodInfoOrderCreate } from '@/components/pages/order/create/good-info/types'
  import moment from 'moment'
  import { useGetFaultByType } from '@/services/pages/know/useFault'
  import { useOrderStore } from '@/store/modules/order'
  import { usePushDown } from '@/store/modules/pushDown'

  const {
    // optionList: userOptionList,
    // getOptionListParam: getUserOptionListParam,
    getOptionListLoading: getUserOptionListLoading,
    getOptionList: getUserOptionList,
  } = useGetMainContactPersonOptionList()
  const {
    optionList: sendRepairUserOptionList,
    getOptionListParam: getSendRepairUserOptionListParam,
    getOptionListLoading: getSendRepairUserOptionListLoading,
    getOptionList: getSendRepairUserOptionList,
  } = useGetMainContactPersonOptionList()
  // const { addrParseResult, addrParse } = useAddrParseService
  const { getRepeatOrderSetFun, repeatOrderObj, getRepeatOrderFun, is_RepeatOrder } = useRepeatOrder
  const { faultTypes, getFaultTypesLoading, getFaultTypes } = useGetFaultTypes()
  const {
    loading: getFaultByTypeLoading,
    faultList,
    getFaultParams,
    getFault,
  } = useGetFaultByType()
  const {
    optionList: sourceOptionList,
    getOptionListParam: getSourceOptionListParam,
    getOptionListLoading: getSourceOptionListLoading,
    getOptionList: getSourceOptionList,
  } = useGetSourceOptionList()
  const { userCreditLimitByOrderTip, getCreditLimit } = useGetUserCreditLimit()
  const { orderDetailToPaste, orderGoodListToPaste, clearCopyInfo, snCodeInfo, clearSnCodeInfo } =
    useOrderStore()
  const { returnFactoryDetail, returnFactoryGood, clearPushDownInfo } = usePushDown()

  defineOptions({
    name: routeComponentName.order.orderCreate,
  })

  // 激活的路由对象
  const route = useRoute()

  const companyNameSelectPopoverVisible = ref(false)
  const allLoading = computed(() => {
    return (
      loading.value ||
      submitLoading.value ||
      getSourceOptionListLoading.value ||
      getFaultTypesLoading.value ||
      getSendRepairUserOptionListLoading.value ||
      getUserOptionListLoading.value ||
      getLoginNetworkIdLoading.value
    )
  })
  const getNetworkOptionsLoading = ref(false)

  // 故障描述快速填充列表
  // const descQuickFillList = [
  //   '尾部线破坏',
  //   '机头起雾',
  //   '不能升降',
  //   '无图像',
  //   '不能控制',
  //   '不能仰俯',
  //   '一边轮子不转',
  //   '不通电',
  //   '顶针环',
  //   '保养',
  // ]

  // 用户状态管理
  const userStore = useUserStore()

  // 视频预览路径集合
  const videoPreviewUrls = ref<Array<string>>([])

  // 视频预览的初始索引
  const videoPreviewInitialIndex = ref(0)

  // 视频预览弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 附件预览路径集合
  const pdfPreviewUrls = ref<Array<string>>([])

  // 附件预览的初始索引
  const pdfPreviewInitialIndex = ref(0)

  // 附件预览弹窗显示状态
  const pdfPreviewModalVisible = ref(false)

  // 设备列表组件实例
  const goodInfoInstance = ref<InstanceType<typeof GoodInfo> | null>(null)

  // 全局路由对象
  const router = useRouter()

  // 自定义字段
  const customFieldList = ref<Array<CustomField>>([])

  // 自定义字段表单组件实例
  const customFieldFormInstance = ref<Array<FormInstance> | null>(null)

  // 基本信息表单组件实例
  const basicInfoFormInstance = ref<FormInstance | null>(null)

  // 基本信息div
  const basicInfoDiv = ref<HTMLDivElement | null>(null)

  // 自定义信息div
  const customInfoDiv = ref<HTMLDivElement | null>(null)

  // 公司信息div
  const customerInfoDiv = ref<HTMLDivElement | null>(null)

  // 设备信息div
  const goodInfoDiv = ref<HTMLDivElement | null>(null)

  // 表单
  const basicData = ref<Form>({
    workSourceId: '',
    moduleId: '', // 工单类型
    overinsured: false, // 质保状态
    content: '', // 故障描述
    userId: '', // 公司ID
    accountNo: '', // 公司账号
    name: '', // 姓名
    phone: '', // 客户电话
    otherPhone: '', // 其他联系方式
    factoryId: '', // 品牌商家ID
    isWorkDay: false,
    customfieldList: [
      {
        contents: [{ id: null, val: null }],
        moduleFieldId: '',
        name: '',
        required: true,
        status: null,
        tip: '',
        type: null,
        uploadQty: null,
        uploadSize: null,
        val: null,
        imgArr: [],
        workFieldId: '',
      },
    ],
    faultTypeRelationVos: [],
    faultRelationVos: [],
    faultReason: [],
    solution: [],
    sendForRepairUsername: '', //报单人信息
    sendForRepairPhone: '', //报单人手机
    repairCompany: '',
    repairCompanyId: '',
    repairCompanyPhone: '',
    address: '',
    addressee: '',
    addresseePhone: '',
    project: '',
    repairGoodsId: '',
    serviceDate: '',
  })

  // 解决措施下拉选项
  const solveOptions = ref<Array<{ id: string; content: string }>>([])

  // 故障原因下拉选项
  const faultReasonOptions = ref<Array<{ id: string; content: string }>>([])

  // 选择的用户是否加入了黑名单
  const isSelectedUserJoinBlackList = ref(false)

  // 当前登录的账号所在的部门
  const loginedAccountNetwork = ref('')

  // 报单公司弹出框显示状态
  const sendRepairUserSelectPopoverVisible = ref(false)

  /**
   * 故障现象描述快速填充项点击事件
   * @param {string} text - 快读填充项文本
   */
  // const handleDescQuickFillItemClick = (text: string) => {
  //   if (basicData.value.content.length < 200) {
  //     basicData.value.content += `${text}、`
  //   }

  //   if (basicData.value.content.length > 200) {
  //     basicData.value.content = basicData.value.content.substring(0, 200)
  //   }
  // }

  /**
   * 报单公司更新事件
   * @param {UserMainContactPersonOption} sendRepairUser - 报单公司
   */
  const handleSendRepairUserChange = (sendRepairUser: UserMainContactPersonOption) => {
    basicData.value.repairCompany = sendRepairUser.name
    basicData.value.repairCompanyId = sendRepairUser.userId
    basicData.value.repairCompanyPhone = sendRepairUser.phone
  }

  /**
   * 清除报单公司信息事件
   */
  const onClearSendRepairUserInfo = () => {
    basicData.value.repairCompanyId = ''
    basicData.value.repairCompany = ''
    basicData.value.repairCompanyPhone = ''
    userPopoverStatus.value = false
  }

  /**
   * 报单公司输入事件
   */
  const handleSendRepairUserInput = _.debounce((keyword: string) => {
    if (keyword.trim()) {
      sendRepairUserSelectPopoverVisible.value = true
      getSendRepairUserOptionListParam.value.name = basicData.value.repairCompany
      getSendRepairUserOptionList()
    }
  }, 500)

  /**
   * 商品信息的更新客户事件
   * @param {CodeInfoByCode} goodAndUserInfo - 客户和商品信息
   */
  const handleGoodInfoChangeUser = (goodAndUserInfo: CodeInfoByCode) => {
    if (goodAndUserInfo) {
      nextTick(() => {
        addrs.value = {
          province: goodAndUserInfo.province,
          city: goodAndUserInfo.city,
          area: goodAndUserInfo.area,
          town: goodAndUserInfo.town,
        }

        if (goodAndUserInfo.userId) {
          basicData.value.userId = goodAndUserInfo.userId
        }

        if (goodAndUserInfo.name) {
          basicData.value.name = goodAndUserInfo.name
        }

        if (goodAndUserInfo.phone) {
          basicData.value.phone = goodAndUserInfo.phone
        }

        if (goodAndUserInfo.address) {
          basicData.value.address = goodAndUserInfo.address
        }
      })
    }
  }

  /**
   * 获取来源下拉选项
   */
  const handleGetSourceOptionList = _.debounce(async (keyword: string) => {
    if (getSourceOptionListParam.value.name !== keyword) {
      getSourceOptionListParam.value.name = keyword
      await getSourceOptionList()
      setSourceFromDefaultOption()
    }
  }, 600)

  /**
   * 附件预览事件
   * @param {Array<string>} urls - 预览路径集合
   * @param {Number} index - 第一个预览文件的索引
   */
  const handlePdfPreview = (urls: Array<string>, index: number) => {
    pdfPreviewUrls.value = urls
    pdfPreviewInitialIndex.value = index
    pdfPreviewModalVisible.value = true
  }

  /**
   * 视频预览事件
   * @param {Array<string>} urls - 预览路径集合
   * @param {Number} index - 第一个预览文件的索引
   */
  const handleVideoPreview = (urls: Array<string>, index: number) => {
    videoPreviewUrls.value = urls
    videoPreviewInitialIndex.value = index
    videoPreviewModalVisible.value = true
  }

  /**
   * 处理类型选择事件
   * @param {Array<string>} value - 分类id
   */
  const handleFaultTypeSelect = (value: Array<string>) => {
    basicData.value.faultTypeRelationVos = value.map((item) => {
      return {
        oneFaultTypeId: item,
        twoFaultTypeId: '',
        threeFaultTypeId: '',
      }
    })
    getFaultParams.value = basicData.value.faultTypeRelationVos
    getFault()
  }

  /**
   * 移除处理类型事件
   * @param {String} val - 分类id
   */
  const handleRemoveFaultType = async (val: string) => {
    getFaultParams.value = [
      {
        oneFaultTypeId: val,
        twoFaultTypeId: '',
        threeFaultTypeId: '',
      },
    ]
    const res = await getFaultByType(getFaultParams.value)
    res.data.data.rows.forEach((item) => {
      removeFaultReasonVoById(item)
    })
  }

  /**
   * 根据故障对象移除故障现象
   * @param {FaultByType} fault - 故障对象
   */
  const removeFaultReasonVoById = (fault: FaultByType) => {
    const faultIndex = basicData.value.faultRelationVos.findIndex(
      (item) => item.faultId === fault.id,
    )
    basicData.value.faultRelationVos.splice(faultIndex, 1)
    removeSolveByIds(fault.solution.map((item) => item.id))
    removeReasonByIds(fault.faultReason.map((item) => item.id))
  }

  /**
   * 根据id列表移除解决措施下拉选项和表单选中的解决措施
   * @param {Array<string>} ids - 解决措施id集合
   */
  const removeSolveByIds = (ids: Array<string>) => {
    solveOptions.value = solveOptions.value.filter((item) => !ids.includes(item.id))
    basicData.value.solution = basicData.value.solution.filter((item) => !ids.includes(item.id))
  }

  /**
   * 根据id列表移除故障原因下拉选项和表单选中的故障原因
   * @param {Array<string>} ids - 解决措施id集合
   */
  const removeReasonByIds = (ids: Array<string>) => {
    faultReasonOptions.value = faultReasonOptions.value.filter((item) => !ids.includes(item.id))
    basicData.value.faultReason = basicData.value.faultReason.filter(
      (item) => !ids.includes(item.id),
    )
  }

  /**
   * 故障现象选择事件
   * @param {Array<string>} value - 选择的值
   */
  const handleFaultPhenomenonChange = (value: Array<string>) => {
    basicData.value.faultRelationVos.length = 0
    value.forEach((id) => {
      faultPhenomenonOptionsAdd(id)
    })
  }

  /**
   * 故障现象移除事件
   * @param {String} id - 故障现象id
   */
  const handleFaultPhenomenonRemove = (id: string) => {
    const faultOption = faultList.value.find((item) => item.id === id)
    if (faultOption) {
      removeSolveByIds(faultOption.solution.map((item) => item.id))
      removeReasonByIds(faultOption.faultReason.map((item) => item.id))
    }
  }

  /**
   * 添加故障原因下拉选项
   */
  const faultReasonOptionsAdd = (options: Array<{ id: string; content: string }>) => {
    options.forEach((option) => {
      if (!faultReasonOptions.value.map((item) => item.id).includes(option.id)) {
        if (option.content) {
          faultReasonOptions.value.push(option)
        }
      }
    })
  }

  /**
   * 添加解决措施下拉选项
   */
  const solveOptionsAdd = (options: Array<{ id: string; content: string }>) => {
    options.forEach((option) => {
      if (!solveOptions.value.map((item) => item.id).includes(option.id)) {
        if (option.content) {
          solveOptions.value.push(option)
        }
      }
    })
  }

  /**
   * 根据故障id添加故障下拉选项并更新表单
   * @param {String} id - 要添加的id
   */
  const faultPhenomenonOptionsAdd = (id: string) => {
    const fault = faultList.value.find((fault) => fault.id === id)
    if (fault) {
      faultReasonOptionsAdd(fault.faultReason)
      solveOptionsAdd(fault.solution)
      const isCanAdd = !basicData.value.faultRelationVos
        .map((relation) => relation.faultId)
        .includes(fault.id)
      if (isCanAdd) {
        basicData.value.faultRelationVos.push({
          faultId: fault.id,
          fault: fault.name,
        })
      }
    } else {
      basicData.value.faultRelationVos.push({
        faultId: `${faultList.value.length}`,
        fault: id,
      })
      faultList.value.push({
        code: '',
        disabled: false,
        faultReason: [],
        id: `${faultList.value.length}`,
        name: id,
        select: true,
        solution: [],
      })
    }
  }

  /**
   * 故障原因选择事件
   * @param {Array<string>} ids - 选择的故障原因
   */
  const handleFaultReasonSelect = (ids: Array<string>) => {
    basicData.value.faultReason.length = 0
    ids.forEach((id) => {
      const faultReason = faultReasonOptions.value.find((item) => item.id === id)
      if (faultReason) {
        basicData.value.faultReason.push(faultReason)
      } else {
        basicData.value.faultReason.push({
          id: `${faultReasonOptions.value.length}`,
          content: `${id}`,
        })
        faultReasonOptions.value.push({
          id: `${faultReasonOptions.value.length}`,
          content: `${id}`,
        })
      }
    })
  }

  /**
   * 解决措施选择事件
   * @param {Array<string>} ids - 选择的解决措施
   */
  const handleSolveSelect = (ids: Array<string>) => {
    basicData.value.solution.length = 0
    ids.forEach((id) => {
      const solve = solveOptions.value.find((item) => item.id === id)
      if (solve) {
        basicData.value.solution.push(solve)
      } else {
        basicData.value.solution.push({
          id: `${solveOptions.value.length}`,
          content: `${id}`,
        })
        solveOptions.value.push({
          id: `${solveOptions.value.length}`,
          content: `${id}`,
        })
      }
    })
  }

  /**
   * 地址识别按钮点击事件
   */
  // const onAddrParse = async () => {
  //   if (!allUserInfo.value.trim()) return
  //   await addrParse(allUserInfo.value.trim())
  //   addrs.value = {
  //     province: addrParseResult.value.province,
  //     city: addrParseResult.value.city,
  //     area: addrParseResult.value.area,
  //     town: addrParseResult.value.town,
  //   }
  //   basicData.value.userId = ''
  //   basicData.value.name = addrParseResult.value.username
  //   basicData.value.phone = addrParseResult.value.phone
  //   basicData.value.address = addrParseResult.value.address
  // }

  /**
   * 显示文件上传的大小错误
   */
  const showFileUploadSizeErrTip = _.debounce((customField: CustomField) => {
    let tip = ''
    if (customField.type === 5) {
      tip = infoTip.order.create.picture_upload_size_err
    }

    if (customField.type === 6) {
      tip = infoTip.order.create.pdf_upload_size_err
    }

    if (customField.type === 7) {
      tip = infoTip.order.create.video_upload_size_err
    }
    HMessageBox.error(tip.replace('$size', String(customField.uploadSize)))
  }, 10)

  /**
   * 显示文件上传的数量错误
   */
  const showFileUploadCountErrTip = _.debounce((customField: CustomField) => {
    let tip = ''
    if (customField.type === 5) {
      tip = infoTip.order.create.picture_upload_count_err
    }

    if (customField.type === 6) {
      tip = infoTip.order.create.pdf_upload_count_err
    }

    if (customField.type === 7) {
      tip = infoTip.order.create.video_upload_count_err
    }
    HMessageBox.error(tip.replace('$num', String(customField.uploadQty)))
  }, 10)

  /**
   * 显示文件上传的类型错误
   */
  const showFileUploadTypeErrTip = _.debounce((customField: CustomField) => {
    let tip = ''
    if (customField.type === 5) {
      tip = infoTip.order.create.picture_upload_type_err
    }

    if (customField.type === 6) {
      tip = infoTip.order.create.pdf_upload_type_err
    }

    if (customField.type === 7) {
      tip = infoTip.order.create.video_upload_type_err
    }
    HMessageBox.error(tip)
  }, 10)

  /**
   * 文件上传事件
   * @param {UploadFile} file - 文件对象
   * @param {Number} index - 表单索引
   */
  const handleUploadFile = (file: UploadFile, index: number) => {
    if (file.raw) {
      return false
    }

    const customField = customFieldList.value[index]
    if (file.raw.size / 1024 / 1024 > customField.uploadSize) {
      showFileUploadSizeErrTip(customField)
      return
    }

    if (customField.fileList.length >= customField.uploadQty) {
      showFileUploadCountErrTip(customField)
      return
    }

    if (customField.type === 5 && !file.raw.type.includes('image')) {
      showFileUploadTypeErrTip(customField)
      return
    }

    if (customField.type === 6 && !file.raw.type.includes('pdf')) {
      showFileUploadTypeErrTip(customField)
      return
    }

    if (customField.type === 7 && !file.raw.type.includes('video')) {
      showFileUploadTypeErrTip(customField)
      return
    }

    customFieldList.value[index].fileList.push({
      file: file.raw,
      url: URL.createObjectURL(file.raw),
    })
  }

  /**
   * 删除文件
   * @param {Number} formIndex - 表单索引
   * @param {Number} fileIndex - 文件索引
   */
  const handleDelFile = (formIndex: number, fileIndex: number) => {
    customFieldList.value[formIndex].fileList.splice(fileIndex, 1)
  }

  /**
   * 日期更新事件
   * @param {Number} formIndex - 表单索引
   */
  const handleChangeDate = (formIndex: number) => {
    const date = customFieldList.value[formIndex].val
    customFieldList.value[formIndex].val = moment(date).format('YYYY-MM-DD')
  }

  /**
   * 日期事件更新事件
   * @param {Number} formIndex - 表单索引
   */
  const handleChangeDateTime = (formIndex: number) => {
    const dateTime = customFieldList.value[formIndex].val
    customFieldList.value[formIndex].val = moment(dateTime).format('YYYY-MM-DD HH:mm')
  }

  const SettingStore = useSettingStore()

  /**
   * 刷新页面
   */
  const refresh = () => {
    SettingStore.setReload()
  }

  const customerInfoFormInstance = ref<FormInstance>()
  const singleAddressRef = ref<InstanceType<typeof SingleAddress> | null>(null) //地址dom

  // const CascaderProps = ref({
  //   value: 'id',
  //   label: 'name',
  //   children: 'selectVos',
  //   disabled: 'select',
  //   checkStrictly: true,
  // })
  const formRef = ref<FormInstance>()
  const submitLoading = ref(false) //提交工单loading
  // const showType = ref(false)
  const grades = ref(null) // 服务级别
  const grade = ref(null) // 服务级别
  const method = ref() // 处理方式
  const network = ref('') // 受理部门
  const now = ref('') // 下单时间
  const fileList = ref([])
  const type = ref('') // 工单模块分类

  // 设备故障图文件对象
  const goodFaultImgFile = ref<{ url: string; file: UploadRawFile | null }>({
    url: '',
    file: null,
  })

  // 设备序列号图文件对象
  const goodCodeImgFile = ref<{ url: string; file: UploadRawFile | null }>({
    url: '',
    file: null,
  })

  // 工单模块下拉选项
  const modules = ref<Array<OrderType>>([])

  const loading = ref(false)
  const types = ref(null) //工单模块分类
  const dialogContract = ref(false) //文件查看弹窗
  const file = ref() //文件
  const methodss = ref(null) // 处理方式
  const networks = ref(null)
  const addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  const submitFormShow = ref(false) //用来判断是否有自定义字段
  const customers = ref() // 受理客服列表
  const customer = ref() // 受理客服
  const createUserDialogVisit = ref(false) // 创建公司弹窗
  const createUserRef = ref()
  // 创建公司对象
  const createUserForm = reactive({
    name: '', // 客户名称
    phone: '', // 客户电话
  })

  // 校验规则
  const rules = reactive({
    moduleId: [{ required: true, message: '请选择工单类型', trigger: ['change', 'blur'] }],
    workSourceId: [{ required: true, message: '请选择工单来源', trigger: ['change', 'blur'] }],
    overinsured: [{ required: true, message: '请选择质保状态', trigger: ['change', 'blur'] }],
    // phone: [
    //   { required: true, message: '请输入客户电话', trigger: ['change', 'blur'] },
    //   {
    //     validator: (rule, value, callback) => {
    //       if (!/^1[3,4,5,6,7,8,9][0-9]{9}$/.test(basicData.value.phone)) {
    //         return callback(new Error('手机号格式错误'))
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
    name: [{ required: true, message: '请输入客户名称', trigger: ['change', 'blur'] }],
    // address: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
    sendForRepairUsername: [
      { required: true, message: '请输入报单人信息', trigger: ['change', 'blur'] },
    ],
    // sendForRepairPhone: [
    //   { required: true, message: '请输入报单人电话', trigger: ['change', 'blur'] },
    //   {
    //     validator: (rule, value, callback) => {
    //       if (!verifyPhone(basicData.value.sendForRepairPhone)) {
    //         return callback(new Error('报单人电话格式错误'))
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
    repairCompany: [
      {
        required: true,
        message: '请选择报单公司',
        trigger: ['change', 'blur'],
      },
    ],
    factoryId: [{ required: true, message: '请选择商家', trigger: ['change', 'blur'] }],
    // customerAddress: [
    //   {
    //     validator: (rule, value, callback) => {
    //       if (!singleAddressRef.value) {
    //         callback(new Error('请选择公司地址'))
    //         return
    //       }
    //       const { province, area, city } = singleAddressRef.value.getSelectAddr()
    //       if (!province || !area || !city) {
    //         callback(new Error('请选择公司地址'))
    //         return
    //       }
    //       callback()
    //     },
    //     trigger: ['change', 'blur'],
    //   },
    // ],
  })

  // 校验规则
  const createUserFormRules = reactive<FormRules>({
    name: [
      { required: true, message: '客户名称不能为空', trigger: ['change', 'blur'] },
      { required: true, max: 100, message: '客户名称长度限制 2~100', trigger: ['change', 'blur'] },
    ],
    phone: [
      { required: true, message: '客户电话不能为空', trigger: ['change', 'blur'] },
      {
        required: true,
        validator: (rule, value, callback) => {
          if (!verifyPhone(createUserForm.phone)) {
            return callback(new Error('手机号格式错误'))
          }
          callback()
        },
        trigger: ['change'],
      },
    ],
  })

  /**
   * 设备故障图删除事件
   */
  const onDelGoodFaultImgFile = () => {
    goodFaultImgFile.value = {
      url: '',
      file: null,
    }
  }

  /**
   * 设备序列号图删除事件
   */
  const onDelGoodSnCodeImgFile = () => {
    goodCodeImgFile.value = {
      url: '',
      file: null,
    }
  }

  // 取消工单
  const onCancelOrder = () => {
    useTagsViewStore().delView(router.currentRoute.value.path)
    router.push({ path: '/order/list' })
  }

  /**
   * 重单字段查询
   */
  const repeatSearch = ref({
    codeIds: [], //设备序列号
    goodsIds: [], //设备IDs
    moduleId: '', //模块ID
    userPhone: '', //客户电话
    username: '', //客户名称
  })
  // /**
  //  * 重单开启字段
  //  */
  // const repeatOrderObj = ref({
  //   enableGoodsModel: true,//型号
  //   enableGoodsName: false,//设备名称
  //   enableOrderModule: false,//工单模块
  //   enableSNCode: false,//序列号、序列号
  //   enableUserName: true,//客户名称
  //   enableUserPhone: true//客户电话
  // })
  // // 获取是否开启重单
  // const getRepeatOrderSetFun = () => {
  //   getRepeatOrderSet().then(res => {
  //     if (res.data.code == 20000) {
  //       repeatOrderObj.value = res.data.data.row
  //     }
  //   })
  // }
  // //型号、设备名称=>1 序列号、序列号=>2  客户名称=>3 客户电话=>4 工单模块=>5
  const is_RepeatOrderArr = ref([])
  // 设备序列号,名称
  const changeGoods = async () => {
    await getRepeatOrderSetFun()
    let codeIds: Array<string> = []
    let goodsIds: Array<string> = []
    is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))

    if (!goodInfoInstance.value) {
      return false
    }

    const orderGoods = goodInfoInstance.value.getGoods()
    orderGoods.map((o) => {
      o.orderGoodsVos.map((i) => {
        if (i.codeIds.length > 0) {
          codeIds.push(...i.codeIds)
        }
        if (i.goodsId) {
          goodsIds.push(i.goodsId)
        }
      })
    })
    if (
      (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) &&
      repeatOrderObj.value.enableSNCode
    ) {
      repeatSearch.value.goodsIds = goodsIds
      repeatSearch.value.codeIds = codeIds
      if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
      is_RepeatOrderArr.value.push(2)
      is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
      if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
        getRepeatOrderFun(repeatSearch.value, true)
    } else if (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) {
      repeatSearch.value.goodsIds = goodsIds
      if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
      is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
      if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
        getRepeatOrderFun(repeatSearch.value, true)
    } else if (repeatOrderObj.value.enableSNCode) {
      repeatSearch.value.codeIds = codeIds
      is_RepeatOrderArr.value.push(2)
      is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
      if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
        getRepeatOrderFun(repeatSearch.value, true)
    } else {
      repeatSearch.value.codeIds = []
      repeatSearch.value.goodsIds = []
      is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))
    }
  }

  const orderSaveFun = async () => {
    // const useAddr = singleAddressRef.value.getSelectAddr()
    // if (!useAddr.province) {
    //   HMessageBox.error(infoTip.order.create.noContactAddress)
    //   return
    // }
    if (!goodInfoInstance.value) {
      return false
    }
    const orderGoods = goodInfoInstance.value.getGoods()
    if (orderGoods.length <= 0) {
      HMessageBox.error(infoTip.order.create.noGood)
      return
    }
    let data: OrderAPIRequest.OrderCreateForm = {
      content: basicData.value.content, //故障描述
      createTime: now.value, //下单时间
      delImageIds: [], //删除的工单附件ID集合
      delOrderGoodsIds: [], //删除的工单设备对象ID集合
      empId: customer.value, //人员表ID，即客服ID
      id: '', //工单ID，新增不必传，修改必传
      imageVos: [],
      moduleId: basicData.value.moduleId, //工单模块ID
      networkId: network.value, //部门表ID
      orderGoodsTypes: orderGoods,
      factoryId: basicData.value.factoryId || '0', // 品牌商家ID
      orderUser: {
        name: basicData.value.name, //客户名称
        otherPhone: '', //其他电话
        phone: basicData.value.phone, //客户电话
        userId: basicData.value.userId, //公司ID
        // province: useAddr.province, //地址-省
        // city: useAddr.city, //地址-市
        // area: useAddr.area, //地址-县/区
        // town: useAddr.town, //地址-镇
        address: basicData.value.address, //公司详细地址
        sendForRepairUsername: basicData.value.sendForRepairUsername, //报单人信息
        sendForRepairPhone: basicData.value.sendForRepairPhone, //报单人手机
        repairCompany: basicData.value.repairCompany, // 报修客户名称
        repairCompanyId: basicData.value.repairCompanyId, // 报修公司ID
        repairCompanyPhone: basicData.value.repairCompanyPhone,
        area: '',
        city: '',
        helpOtherCreateOrder: false,
        province: '',
        town: '',
      },
      overinsured: basicData.value.overinsured, //质保状态，是否保外：false-保内，true-保外
      workSourceId: basicData.value.workSourceId, //工单来源
      threeTypeId: '', //工单模块分类ID3
      threeWayId: '', //工单模块方式ID3
      twoTypeId: '', //工单模块分类ID2
      twoWayId: '', //工单模块方式ID2
      oneTypeId: '', //工单模块分类ID1
      oneWayId: '', //工单模块方式ID1
      workLevelId: grade.value || '', //工单级别ID
      workFieldVal: [], //工单自定义字段值对象,
      faultRelationVos: basicData.value.faultRelationVos.map((item) => {
        // 如果id的位数小于5位就说明这个选项是动态新增的，需要将id重置为0
        if (item.faultId.length <= 5) {
          return {
            faultId: '0',
            fault: item.fault,
          }
        }
        return item
      }),
      isWorkDay: basicData.value.isWorkDay,
      faultReason: basicData.value.faultReason,
      solution: basicData.value.solution,
      faultTypeRelationVos: basicData.value.faultTypeRelationVos,
      workImages: [],
      address: basicData.value.address,
      addressee: basicData.value.addressee,
      addresseePhone: basicData.value.addresseePhone,
      project: basicData.value.project,
      repairGoodsId: basicData.value.repairGoodsId,
      serviceDate: basicData.value.serviceDate,
    }
    if (data.faultReason.length && !faultReasonOptions.value.length) {
      data.faultReason = [{ id: 0, content: data.faultReason }]
    }

    if (data.solution.length && !solveOptions.value.length) {
      data.solution = [{ id: 0, content: data.solution }]
    }
    // 工单模块分类
    if (type.value?.length > 0) {
      type.value.map((o, i) => {
        if (i == 0) {
          data.oneTypeId = o
        }
        if (i == 1) {
          data.twoWayId = o
        }
        if (i == 2) {
          data.threeTypeId = o
        }
      })
    }
    // 工单模块方式
    if (method.value?.length > 0) {
      method.value.map((o, i) => {
        if (i == 0) {
          data.oneWayId = o
        }
        if (i == 1) {
          data.twoWayId = o
        }
        if (i == 2) {
          data.threeWayId = o
        }
      })
    }
    submitLoading.value = true
    // 判断是否有图片
    if (fileList.value?.length > 0) {
      // 获取文件列表
      const imageList = fileList.value
        .filter((item) => !!item.file)
        .map((o) => {
          return o.file
        })
      data.imageVos = []

      // 如果有文件上传就调用文件上传接口
      if (imageList.length > 0) {
        const orderAnnexUploadRes = await orderAnnexUpload(imageList)
        if (orderAnnexUploadRes.data.success) {
          for (let i = 0; i < orderAnnexUploadRes.data.data.rows.length; i++) {
            data.imageVos.push({ id: null, image: orderAnnexUploadRes.data.data.rows[i], type: 1 })
          }
        } else {
          HMessageBox.error(orderAnnexUploadRes.data.message)
        }
      }

      // 如果文件链接包含了http就说明是从另外一张工单复制过来的，就直接添加到表单中
      const imgUrls = fileList.value
        .filter((img) => img.image.includes('http'))
        .map((img) => img.image)
      if (imgUrls.length > 0) {
        imgUrls.forEach((img) => {
          data.imageVos.push({ id: null, image: img, type: 1 })
        })
      }
    }

    if (goodCodeImgFile.value.file) {
      const res = await orderAnnexUpload([goodCodeImgFile.value.file])
      if (res.data.code === 20000) {
        data.imageVos.push({
          id: null,
          type: 3,
          image: res.data.data.rows[0],
        })
      }
    }

    if (goodCodeImgFile.value.url.includes('http')) {
      data.imageVos.push({
        id: null,
        type: 3,
        image: goodCodeImgFile.value.url,
      })
    }

    if (goodFaultImgFile.value.file) {
      const res = await orderAnnexUpload([goodFaultImgFile.value.file])
      if (res.data.code === 20000) {
        data.imageVos.push({
          id: null,
          type: 4,
          image: res.data.data.rows[0],
        })
      }
    }

    if (goodFaultImgFile.value.url.includes('http')) {
      data.imageVos.push({
        id: null,
        type: 4,
        image: goodFaultImgFile.value.url,
      })
    }

    // 自定义字段文件上传
    const customFieldFileList = customFieldList.value.filter((field) =>
      [5, 6, 7].includes(field.type),
    )
    for (let index = 0; index < customFieldFileList.length; index++) {
      let optionVos: Array<{ id: string; optValue: string }> = []
      if (customFieldFileList[index].type === 7) {
        const orderVideoUploadRes = await orderVideoUpload(
          customFieldFileList[index].fileList.map((file) => file.file),
        )
        if (orderVideoUploadRes.data.code === 20000) {
          optionVos = orderVideoUploadRes.data.data.rows.map((item) => {
            return {
              id: '',
              optValue: item,
            }
          })
        } else {
          HMessageBox.error(orderVideoUploadRes.data.message)
        }
      }

      if (customFieldFileList[index].type === 5 || customFieldFileList[index].type === 6) {
        const orderAnnexUploadRes = await orderAnnexUpload(
          customFieldFileList[index].fileList.map((file) => file.file),
        )
        if (orderAnnexUploadRes.data.code === 20000) {
          optionVos = orderAnnexUploadRes.data.data.rows.map((item) => {
            return {
              id: '',
              optValue: item,
            }
          })
        } else {
          HMessageBox.error(orderAnnexUploadRes.data.message)
        }
      }

      data.workFieldVal.push({
        id: '',
        moduleFieldId: customFieldFileList[index].moduleFieldId,
        name: customFieldFileList[index].name,
        type: customFieldFileList[index].type,
        workFieldId: customFieldFileList[index].workFieldId,
        optionVos,
      })
    }

    // 自定义字段（文本、多行文本、单选、评分、日期、日期时间）
    customFieldList.value
      .filter((field) => [1, 2, 3, 8, 9, 10].includes(field.type))
      .forEach((field) => {
        data.workFieldVal.push({
          id: '',
          moduleFieldId: field.moduleFieldId,
          name: field.name,
          type: field.type,
          workFieldId: field.workFieldId,
          optionVos: [
            {
              id: '',
              optValue: field.val,
            },
          ],
        })
      })

    // 自定义字段（多选）
    customFieldList.value
      .filter((field) => field.type === 4)
      .forEach((field) => {
        data.workFieldVal.push({
          id: '',
          moduleFieldId: field.moduleFieldId,
          name: field.name,
          type: field.type,
          workFieldId: field.workFieldId,
          optionVos: field.valList.map((value) => {
            return {
              id: '',
              optValue: value,
            }
          }),
        })
      })

    await addSave(data).then((res) => {
      ElMessage({
        message: res.data.success ? '提交工单成功' : res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 5000,
        showClose: true,
        plain: true,
      })
      if (res.data.code === 20000) {
        repeatSearch.value = {
          codeIds: [], //设备序列号
          goodsIds: [], //设备IDs
          moduleId: '', //模块ID
          userPhone: '', //客户电话
          username: '', //客户名称
        }
        is_RepeatOrderArr.value = []
        useTagsViewStore().delView(router.currentRoute.value.path)
        refresh()
        goodInfoInstance.value.clear()
        if (res.data.data.id) {
          router.push(`/order/odetail/${res.data.data.id}`)
        } else {
          router.push({ path: '/order/list' })
        }
      }
    })
    submitLoading.value = false
  }

  /**
   * 设备故障图上传事件
   * @param {UploadFile} file - 文件对象
   */
  const handleUploadGoodFaultImg = (file: UploadFile) => {
    goodFaultImgFile.value.file = file.raw
    goodFaultImgFile.value.url = URL.createObjectURL(file.raw)
  }

  /**
   * 设备序列号图上传事件
   * @param {UploadFile} file - 文件对象
   */
  const handleUploadGoodCodeImg = (file: UploadFile) => {
    goodCodeImgFile.value.file = file.raw
    goodCodeImgFile.value.url = URL.createObjectURL(file.raw)
  }

  /**
   * 提交工单
   */
  const submitOrder = async () => {
    if (isSelectedUserJoinBlackList.value) {
      HMessageBox.error(infoTip.order.create.user_joined_back_list)
      return
    }

    if (!basicInfoFormInstance.value) {
      return
    }

    if (!customerInfoFormInstance.value) {
      return
    }

    if (customFieldList.value.length > 0) {
      if (!customFieldFormInstance.value || customFieldFormInstance.value.length <= 0) {
        return
      }
    }

    if (!goodInfoInstance.value) {
      return
    }

    const { userId, name } = basicData.value
    if (userId && name) {
      const userCreditLimitErrMsg = await judgeUserCreditLimit(userId, name)
      if (userCreditLimitErrMsg) {
        HMessageBox.error(userCreditLimitErrMsg)
        return
      }
    }

    try {
      await basicInfoFormInstance.value.validate()
    } catch (error) {
      basicInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
      return false
    }

    if (customFieldList.value.length > 0) {
      try {
        for (let i = 0; i < customFieldFormInstance.value.length; i++) {
          await customFieldFormInstance.value[i].validate()
        }
      } catch (error) {
        customInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
        return false
      }
    }

    try {
      await customerInfoFormInstance.value.validate()
    } catch (error) {
      customerInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
      return false
    }

    const orderGoods = goodInfoInstance.value.getGoods()
    if (orderGoods.length <= 0) {
      HMessageBox.error(infoTip.order.create.noGood)
      goodInfoDiv.value.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'start' })
      return
    }

    await getRepeatOrderSetFun()
    is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 3 || o == 4))
    if (repeatOrderObj.value.enableUserPhone && repeatOrderObj.value.enableUserName) {
      repeatSearch.value.userPhone = basicData.value.phone
      repeatSearch.value.username = basicData.value.name
      if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
      if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
    } else if (repeatOrderObj.value.enableUserName) {
      repeatSearch.value.username = basicData.value.name
      if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
    } else if (repeatOrderObj.value.enableUserPhone) {
      repeatSearch.value.userPhone = basicData.value.phone
      if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
    }
    is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => o !== 5)
    if (repeatOrderObj.value.enableOrderModule) {
      repeatSearch.value.moduleId = basicData.value.moduleId
      if (repeatSearch.value.moduleId) is_RepeatOrderArr.value.push(5)
    }

    let codeIds = []
    let goodsIds = []
    is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))
    orderGoods.map((o) => {
      o.orderGoodsVos.map((i) => {
        if (i.codeIds.length > 0) {
          codeIds.push(...i.codeIds)
        }
        if (i.goodsId) {
          goodsIds.push(i.goodsId)
        }
      })
    })
    if (
      (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) &&
      repeatOrderObj.value.enableSNCode
    ) {
      repeatSearch.value.goodsIds = goodsIds
      repeatSearch.value.codeIds = codeIds
      if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
      is_RepeatOrderArr.value.push(2)
    } else if (repeatOrderObj.value.enableGoodsModel || repeatOrderObj.value.enableGoodsName) {
      repeatSearch.value.goodsIds = goodsIds
      if (repeatSearch.value.goodsIds.length > 0) is_RepeatOrderArr.value.push(1)
    } else if (repeatOrderObj.value.enableSNCode) {
      repeatSearch.value.codeIds = codeIds
      is_RepeatOrderArr.value.push(2)
    } else {
      repeatSearch.value.codeIds = []
      repeatSearch.value.goodsIds = []
      is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 1 || o == 2))
    }
    is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
    if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort())) {
      let is_repeat = await getRepeatOrderFun(repeatSearch.value)
      if (is_repeat.code) {
        if (is_repeat.val) {
          ElMessageBox.confirm('存在重复工单，是否继续报单？', '提示', {
            type: 'warning',
            icon: markRaw(WarningFilled),
            confirmButtonText: '继续',
            cancelButtonText: '取消',
          })
            .then(() => {
              orderSaveFun()
            })
            .catch(() => {
              return
            })
          return
        } else {
          ElMessageBox.confirm('存在重复工单，不允许报单!', '提示', {
            type: 'error',
            icon: markRaw(CircleCloseFilled),
            showCancelButton: false,
          })
          return
        }
      }
      orderSaveFun()
    } else {
      orderSaveFun()
    }
  }

  /**
   * 工单图片上传失败错误信息提示
   * @param {'type' | 'size' | 'count'} type - 提示类型
   */
  const orderPictureUploadFailIntoTip = _.debounce((type: 'type' | 'size' | 'count') => {
    switch (type) {
      case 'type':
        HMessageBox.error(infoTip.order.create.order_picture_upload_type_err)
        break
      case 'size':
        HMessageBox.error(infoTip.order.create.order_picture_upload_size_err)
        break
      case 'count':
        HMessageBox.error(infoTip.order.create.order_picture_upload_count_err)
        break
    }
  }, 100)

  /**
   * 上传工单图片事件
   * @param {UploadFile} uploadFile - 文件对象
   */
  const handleUploadOrderPicture = (uploadFile: UploadFile) => {
    if (!uploadFile.raw.type.includes('image')) {
      orderPictureUploadFailIntoTip('type')
      return
    }

    if (uploadFile.raw.size / 1024 / 1024 > 50) {
      orderPictureUploadFailIntoTip('size')
      return
    }

    if (fileList.value.length >= 10) {
      orderPictureUploadFailIntoTip('count')
      return
    }
    let { uid, name } = uploadFile.raw
    let tmp = {
      uid,
      name,
      image: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
      upDatatime: new Date(Date.now()).toISOString().split('T')[0],
    }
    fileList.value.push(tmp)
  }

  /**
   * 删除图片
   * @param {Number} index - 工单图片索引
   */
  const handleDelOrderPicture = (index: number) => {
    fileList.value.splice(index, 1)
    fileList.value = fileList.value.filter((o, i) => i != index)
  }

  //工单分类下拉数据
  const getworkModuleTypePageSelect = async (val, id) => {
    if (!id) return
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleTypePageSelect(data, id)
    types.value = res.data.data.rows
  }

  //工单分类下拉远程搜索
  // const inputChangeType = async (val) => {
  //   if (basicData.value.moduleId) {
  //     await getworkModuleTypePageSelect(val, basicData.value.moduleId)
  //   }
  // }

  // 处理方式下拉远程搜索
  // const inputChangeMethod = async (val) => {
  //   if (val && basicData.value.moduleId) {
  //     await getworkModuleWayPageSelect(val, basicData.value.moduleId)
  //   }
  // }

  // 获取工单类型下拉选项请求参数
  const getOrderTypeOptionsParam = ref({
    limit: 0,
    page: 0,
    name: '',
  })

  /**
   * 获取工单类型下拉选项
   */
  const handleGetOrderTypeOptions = _.throttle((query: string) => {
    if (query === getOrderTypeOptionsParam.value.name) {
      return false
    }
    getOrderTypeOptionsParam.value.name = query
    getOrderTypeOptionsFn()
  }, 500)

  /**
   * 获取工单类型下拉选项方法
   */
  const getOrderTypeOptionsFn = async () => {
    loading.value = true
    const res = await workModulePageSelect(getOrderTypeOptionsParam.value)
    if (res.data.success) {
      modules.value = res.data.data.rows
    }
    loading.value = false
  }

  /**
   * 获取自定义字段
   * @param {String} moduleId 工单模块id
   */
  const getCustomField = async (moduleId: string) => {
    if (!moduleId) {
      return
    }

    const res = await getModuleField(moduleId)
    submitFormShow.value = res.data.data.row.length > 0
    customFieldList.value = res.data.data.row.map((field, index) => {
      return {
        contents: field.contents,
        moduleFieldId: field.moduleFieldId,
        name: field.name,
        required: field.required,
        status: field.status,
        tip: field.tip,
        type: field.type,
        uploadQty: field.uploadQty,
        uploadSize: field.uploadSize,
        workFieldId: field.workFieldId,
        formCustomFieldIndex: index,
        val: '',
        valList: [],
        fileList: [],
      }
    })
  }

  /**
   * 切换工单类型
   * @param {Object} val - 工单模块
   */
  const handleChangeModule = (val: OrderType) => {
    type.value = val.type
    basicData.value.overinsured = val.overinsured
    // if (val.autoDispatchClient) {
    //   customer.value = 0
    // }
    // if (val.autoDispatchNetwork) {
    //   network.value = ''
    // }
    getworkModuleWayPageSelect('', val.id)
    getworkModuleTypePageSelect('', val.id)
    getCustomField(val.id)
    nextTick(() => {
      formRef.value?.resetFields()
    })
  }

  /**
   * 获取服务级别下拉选项
   */
  const getworkLevelPageSelect = _.throttle((val) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    workLevelPageSelect(data).then((res) => {
      if (res.data.success) {
        grades.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  /**
   * 工单客服组下拉列表查询
   */
  const getworkTeamPageSelect = _.throttle((val: string) => {
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    loading.value = true
    empPageSelecct(data).then((res) => {
      if (res.data.success) {
        customers.value = res.data.data.rows
      }
      loading.value = false
    })
  }, 500)

  /**
   * 获取部门下拉选项
   */
  const getNetworkPageSelectList = _.throttle((val: string) => {
    let data = {
      limit: 100,
      name: val,
      page: 1,
    }
    getNetworkOptionsLoading.value = true
    getNetworkPageSelect(data)
      .then((res) => {
        if (res.data.success) {
          networks.value = res.data.data.rows
        }
      })
      .finally(() => {
        getNetworkOptionsLoading.value = false
      })
  }, 500)

  // 保存新公司
  const onSaveCreateUser = (formEl: FormInstance) => {
    formEl.validate((valid) => {
      if (!valid) {
        return
      }
      onClearUser()
      basicData.value.userId = '0'
      basicData.value.accountNo = createUserForm.phone
      basicData.value.name = createUserForm.name
      basicData.value.phone = createUserForm.phone
      createUserDialogVisit.value = false
    })
  }
  // ***************公司列表搜索************
  const visibleSearch = ref(false)

  const getUserOptionsLoading = ref(false)
  const userOptions = ref<Array<CustomerOption>>([])
  const userPopoverStatus = ref(false)

  /**
   * 客户名称输入事件
   * @param {string} keyword - 搜索关键字
   */
  const handleCompanyNameInput = _.debounce((keyword: string) => {
    if (keyword.trim()) {
      companyNameSelectPopoverVisible.value = true
      basicData.value.name = keyword.trim()
      getUserOptions()
    }
  }, 600)

  const getUserOptions = async () => {
    getUserOptionsLoading.value = true
    const res = await getUserSelect({
      limit: 0,
      name: basicData.value.name,
      page: 0,
    })
    getUserOptionsLoading.value = false
    if (res.data.code === 20000) {
      userOptions.value = res.data.data.rows
    }
  }

  /**
   * 根据公司的信用额度来判断是否允许创建工单
   * @param {string} userId - 公司id
   * @param {string} userName - 公司名
   */
  const judgeUserCreditLimit = async (userId: string, userName: string) => {
    await getCreditLimit(userId)
    const { allowCreateOrderWithSureEndOrder, creditLimitType, unpaidPrice, limitType } =
      userCreditLimitByOrderTip.value
    if (!allowCreateOrderWithSureEndOrder) {
      if (creditLimitType === 2) {
        return `公司（${userName}）还有${unpaidPrice.toFixed(2)}元的账款未结清，不允许创建工单`
      }

      if (creditLimitType === 3) {
        if (limitType === 2) {
          return `公司（${userName}）的信用额度已超出限制，不允许创建工单`
        }

        if (limitType === 3) {
          return `公司（${userName}）还有${unpaidPrice.toFixed(
            2,
          )}元的账款已逾期未结清，不允许创建工单`
        }

        return ''
      }

      return ''
    }
    return ''
  }

  /**
   * 客户名称选择事件
   * @param {UserMainContactPersonOption} user - 选择的公司
   */
  const handleCompanySelect = async (user: UserMainContactPersonOption) => {
    companyNameSelectPopoverVisible.value = false

    if (user) {
      isSelectedUserJoinBlackList.value = user.blacklist
      if (user.blacklist) {
        HMessageBox.error(infoTip.order.create.user_joined_back_list)
      }

      nextTick(() => {
        addrs.value = {
          province: user.province,
          city: user.city,
          area: user.area,
          town: user.town,
        }
      })
      if (user.userId) {
        basicData.value.userId = user.userId
      }

      if (user.name) {
        basicData.value.name = user.name
      }

      if (user.phone) {
        basicData.value.phone = user.phone
      }

      if (user.address) {
        basicData.value.address = user.address
      }

      const errMsg = await judgeUserCreditLimit(user.userId, user.username)
      if (errMsg) {
        HMessageBox.error(errMsg)
      }
    }
  }

  const onClearUserInfo = () => {
    nextTick(() => {
      addrs.value = {
        province: '',
        city: '',
        area: '',
        town: '',
      }
    })
    basicData.value.userId = ''
    basicData.value.name = ''
    basicData.value.phone = ''
    basicData.value.address = ''
    if (singleAddressRef.value) {
      singleAddressRef.value.clearSelectAddr()
    }

    userPopoverStatus.value = false
  }

  // 清除公司账号
  const onClearUser = () => {
    basicData.value.name = ''
    basicData.value.userId = ''
    basicData.value.accountNo = ''
    singleAddressRef.value.clearSelectAddr()
  }

  //  通过模块id 获取处理方式
  const getworkModuleWayPageSelect = async (val, id) => {
    if (!id) return
    let data = {
      limit: 0,
      name: val,
      page: 0,
    }
    const res = await workModuleWayPageSelect(data, id)
    methodss.value = res.data.data.rows
  }
  // 工单分类下拉框出现/隐藏时触发
  // const changeType = async () => {
  //   showType.value = !showType.value
  //   if (!showType.value) {
  //     if (!(type.value instanceof Array)) {
  //       await getworkModuleTypePageSelect('', basicData.value.moduleId)
  //     }
  //   }
  // }
  // 处里方式下拉框出现/隐藏时触发
  // const changeMmethod = async () => {
  //   showType.value = !showType.value
  //   if (!showType.value) {
  //     if (!(method.value instanceof Array)) {
  //       await getworkModuleWayPageSelect('', basicData.value.moduleId)
  //     }
  //   }
  // }

  // 用户的整段信息，包含姓名、手机号、地址
  // const allUserInfo = ref('')

  /**
   * 将来源下拉选项的默认值填充到表单里
   */
  const setSourceFromDefaultOption = () => {
    if (!basicData.value.workSourceId) {
      const defaultSelectedSource = sourceOptionList.value.find((option) => option.select)
      if (defaultSelectedSource && defaultSelectedSource.select) {
        basicData.value.workSourceId = defaultSelectedSource.id
      }
    }
  }

  const getLoginNetworkIdLoading = ref(false)

  /**
   * 获取登录的账号所在的部门id
   */
  const getLoginedNetworkId = async () => {
    try {
      getLoginNetworkIdLoading.value = true
      const res = await getLoginAccountNetworkId()
      getLoginNetworkIdLoading.value = false
      network.value = res.data.data.row
      loginedAccountNetwork.value = res.data.data.row
    } catch (error) {
      getLoginNetworkIdLoading.value = false
    }
  }

  /**
   * 工单信息和工单商品列表粘贴回调
   */
  const pasteOrderInfoFromClipboard = async () => {
    console.log(orderDetailToPaste)
    console.log(orderGoodListToPaste)
    if (!orderDetailToPaste || !orderGoodListToPaste) {
      return
    }

    await getOrderTypeOptionsFn()

    basicData.value.name = orderDetailToPaste.name
    basicData.value.phone = orderDetailToPaste.phone
    basicData.value.userId = orderDetailToPaste.userId
    basicData.value.repairCompany = orderDetailToPaste.repairCompany
    basicData.value.repairCompanyPhone = orderDetailToPaste.repairCompanyPhone
    basicData.value.sendForRepairUsername = orderDetailToPaste.sendForRepairUsername
    basicData.value.sendForRepairPhone = orderDetailToPaste.sendForRepairPhone
    basicData.value.moduleId = orderDetailToPaste.moduleId
    if (
      sourceOptionList.value
        .filter((item) => !item.disabled)
        .map((item) => item.id)
        .includes(orderDetailToPaste.moduleId)
    ) {
      basicData.value.workSourceId = orderDetailToPaste.workSourceId
    }
    network.value = String(orderDetailToPaste.networkId) === '0' ? '' : orderDetailToPaste.networkId
    basicData.value.content = orderDetailToPaste.content
    fileList.value = orderDetailToPaste.orderImages
      .filter((image) => image.includes('http'))
      .map((image) => {
        return {
          uuid: '',
          name: (image.split('/').at(-1) || '').split('.')[0],
          image,
          file: null,
          upDatatime: '',
        }
      })

    const goodFaultImg = orderDetailToPaste.workImages.find((item) => item.type === 3)
    if (goodFaultImg) {
      goodFaultImgFile.value = {
        url: goodFaultImg.image,
        file: null,
      }
    }

    const goodSnCodeImg = orderDetailToPaste.workImages.find((item) => item.type === 4)
    if (goodSnCodeImg) {
      goodCodeImgFile.value = {
        url: goodSnCodeImg.image,
        file: null,
      }
    }

    if (!goodInfoInstance.value) {
      return
    }

    orderGoodListToPaste.forEach((good: OrderDetailAPIResponse.GoodListItem) => {
      const addRow: TableDataGoodInfoOrderCreate = {
        code: '',
        goodsName: good.goodsName,
        goodsSpecName: good.goodsSpec,
        goodsBrand: good.goodsBrand,
        qty: good.qty,
        img: '',
        buyTime: good.buyTime,
        name: good.userName,
        phone: good.userPhone,
        province: good.province,
        city: good.city,
        area: good.area,
        town: good.town,
        address: good.address,
        isEmptyLine: false,
        type: 2,
        goodId: good.goodsId,
        goodSpecId: good.goodsSpecId,
        codeId: '',
        goodsSpecCode: good.goodsCode,
        warrantyStartTime: good.buyTime,
        warrantyEndTime: good.endTime,
        buyMarket: '',
        dl: good.dl || '',
        specialBz: good.specialBz || '',
        standard: good.standard || '',
        voltage: good.voltage || '',
        xlh: good.xlh || '',
        tableType: 0,
        contractNo: '',
      }

      if (good.codes && good.codes.length > 0) {
        good.codes.forEach((code) => {
          Object.assign(addRow, {
            code: code.securityCode,
            type: good.userId ? 1 : 2,
            codeId: code.id,
            warrantyDay: code.warrantyDay,
            userId: good.userId,
          })
          if (goodInfoInstance.value) {
            goodInfoInstance.value.addGood(addRow)
          }
        })
      } else {
        if (goodInfoInstance.value) {
          goodInfoInstance.value.addGood(addRow)
        }
      }
    })

    clearCopyInfo()
  }

  const pasteOrderInfoFromReturnFactory = () => {
    if (!returnFactoryGood) {
      return false
    }

    if (goodInfoInstance.value && returnFactoryDetail) {
      basicData.value = {
        workSourceId: '',
        moduleId: '', // 工单类型
        overinsured: false, // 质保状态
        content: '', // 故障描述
        userId: '', // 公司ID
        accountNo: '', // 公司账号
        name: '', // 姓名
        phone: '', // 客户电话
        otherPhone: returnFactoryDetail.otherPhone, // 其他联系方式
        factoryId: '', // 品牌商家ID
        isWorkDay: false,
        customfieldList: [],
        faultTypeRelationVos: [],
        faultRelationVos: [],
        faultReason: [],
        solution: [],
        sendForRepairUsername: '', //报单人信息
        sendForRepairPhone: '', //报单人手机
        repairCompany: returnFactoryDetail.repairCompanyName,
        repairCompanyId: returnFactoryDetail.repairCompanyId,
        repairCompanyPhone: returnFactoryDetail.repairCompanyPhone,
        address: returnFactoryDetail.address,
        addressee: '',
        addresseePhone: '',
        project: '',
        repairGoodsId: returnFactoryGood.id,
      }

      goodInfoInstance.value.addGood({
        code: returnFactoryGood.code,
        goodsName: returnFactoryGood.goodsName,
        goodsSpecName: returnFactoryGood.goodsSpec,
        goodsBrand: returnFactoryGood.goodsBrand,
        qty: returnFactoryGood.qty,
        img: '',
        buyTime: returnFactoryGood.warrantyStartTime,
        name: returnFactoryGood.username || '',
        phone: returnFactoryGood.userPhone || '',
        province: returnFactoryGood.province || '',
        city: returnFactoryGood.city || '',
        area: returnFactoryGood.area || '',
        town: '',
        address: returnFactoryGood.address || '',
        isEmptyLine: false,
        type: 1,
        goodId: returnFactoryGood.goodsId,
        goodSpecId: returnFactoryGood.goodsSpecId,
        codeId: returnFactoryGood.codeId,
        goodsSpecCode: returnFactoryGood.goodsCode,
        warrantyEndTime: returnFactoryGood.warrantyEndTime,
        warrantyStartTime: returnFactoryGood.warrantyStartTime,
        buyMarket: '',
        dl: returnFactoryGood.dl,
        specialBz: returnFactoryGood.specialBz,
        standard: returnFactoryGood.standard,
        voltage: returnFactoryGood.voltage,
        xlh: returnFactoryGood.xlh,
        contractNo: returnFactoryGood.contractNo || '',
        tableType: 0,
      })
    }

    clearPushDownInfo()
  }

  // 监听处里方式下拉选择
  watch(
    () => method.value,
    (n) => {
      if (!n) {
        getworkModuleWayPageSelect('', basicData.value.moduleId)
      }
    },
  )

  // 监听工单分类下拉选择
  watch(
    () => type.value,
    (n) => {
      if (!n) {
        getworkModuleTypePageSelect('', basicData.value.moduleId)
      }
    },
  )

  // 工单模块
  watch(
    () => basicData.value.moduleId,
    async (n) => {
      await getRepeatOrderSetFun()
      if (repeatOrderObj.value.enableOrderModule) {
        repeatSearch.value.moduleId = n
        if (repeatSearch.value.moduleId) is_RepeatOrderArr.value.push(5)
        is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
        if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
          getRepeatOrderFun(repeatSearch.value, true)
      }
    },
  )

  // 客户电话, 客户名称
  watch([() => basicData.value.phone, () => basicData.value.name], (n) => {
    if (customerInfoFormInstance.value) {
      customerInfoFormInstance.value.validateField(['phone', 'name'], async (v) => {
        if (v) {
          await getRepeatOrderSetFun()
          is_RepeatOrderArr.value = is_RepeatOrderArr.value.filter((o) => !(o == 3 || o == 4))
          if (repeatOrderObj.value.enableUserPhone && repeatOrderObj.value.enableUserName) {
            repeatSearch.value.userPhone = n[0]
            repeatSearch.value.username = n[1]
            if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
            if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
            is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
            if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
              getRepeatOrderFun(repeatSearch.value, true)
          } else if (repeatOrderObj.value.enableUserName) {
            repeatSearch.value.username = n[1]
            if (repeatSearch.value.username) is_RepeatOrderArr.value.push(3)
            is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
            if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
              getRepeatOrderFun(repeatSearch.value, true)
          } else if (repeatOrderObj.value.enableUserPhone) {
            repeatSearch.value.userPhone = n[0]
            if (repeatSearch.value.userPhone) is_RepeatOrderArr.value.push(4)
            is_RepeatOrderArr.value = [...new Set(is_RepeatOrderArr.value)]
            if (_.isEqual(is_RepeatOrder.value, is_RepeatOrderArr.value.sort()))
              getRepeatOrderFun(repeatSearch.value, true)
          }
        }
      })
    }
  })

  // 请求获取下拉数据
  onMounted(() => {
    getSourceOptionList().then(() => {
      setSourceFromDefaultOption()
    })
    getFaultTypes()
    // getUserOptions()
    getSendRepairUserOptionList()
    getUserOptionList()
    getOrderTypeOptionsFn()
    handleGetOrderTypeOptions('')
    if (userStore.isCurrentRoleNetwork) {
      getLoginedNetworkId()
    }
    let data = {
      limit: 0,
      name: '',
      page: 0,
    }
    loading.value = true
    workLevelPageSelect(data)
      .then((res) => {
        if (res.data.success) {
          grades.value = res.data.data.rows
          if (grades.value) {
            grades.value.filter((o) => {
              if (o.select) {
                grade.value = o.id
              }
            })
          }
        }
      })
      .finally(() => {
        loading.value = false
      })
    getworkTeamPageSelect('')
    getNetworkPageSelectList('')
    // 设置当前时间
    now.value =
      new Date(Date.now()).toISOString().split('T')[0] +
      ' ' +
      new Date(Date.now()).toTimeString().split(' ')[0]
    if (route.query.pushDownFromReturn === '1') {
      pasteOrderInfoFromReturnFactory()
    }

    if (route.query.mode === 'orderCopy') {
      pasteOrderInfoFromClipboard()
    }

    if (route.query.mode === 'snCode' && goodInfoInstance.value && snCodeInfo) {
      goodInfoInstance.value.addGood({
        code: snCodeInfo.securityCode,
        contractNo: snCodeInfo.contractNo,
        goodsName: snCodeInfo.goodsName,
        goodsSpecName: snCodeInfo.goodsSpecName,
        goodsBrand: snCodeInfo.brand,
        qty: 1,
        img: '',
        buyTime: snCodeInfo.warrantyStartTime,
        name: snCodeInfo.username,
        phone: snCodeInfo.phone,
        province: snCodeInfo.province,
        city: snCodeInfo.city,
        area: snCodeInfo.area,
        town: snCodeInfo.town,
        address: snCodeInfo.address,
        isEmptyLine: false,
        type: snCodeInfo.register ? 1 : 2,
        goodId: snCodeInfo.goodsId,
        goodSpecId: snCodeInfo.goodsSpecId,
        codeId: snCodeInfo.id,
        goodsSpecCode: snCodeInfo.goodsCode,
        warrantyStartTime: snCodeInfo.warrantyStartTime,
        warrantyEndTime: snCodeInfo.warrantyEndTime,
        buyMarket: '',
        dl: snCodeInfo.dl,
        specialBz: snCodeInfo.specialBz,
        standard: snCodeInfo.standard,
        voltage: snCodeInfo.voltage,
        xlh: snCodeInfo.xlh,
        tableType: 0,
      })
    }
  })

  onUnmounted(() => {
    file.value = 'about:blank'
  })
</script>

<style lang="scss" scoped>
  .select-header {
    display: flex;
    column-gap: 5px;
  }

  .fault-phenomenon-option {
    display: flex;
    column-gap: 5px;
  }

  .user-options-wrapper {
    .user-options {
      .user-option {
        height: 35px;
        display: flex;
        column-gap: 12px;
        cursor: pointer;
        padding: 8px 10px;
        box-sizing: border-box;

        &:hover {
          background-color: #f5f7fa;
        }

        .user-name {
          width: 80px;
        }

        .is-join-black-list,
        .user-phone {
          line-height: 19px;
        }
      }
    }
  }

  .order-create-form-wrapper {
    width: 100%;
    height: calc(100vh - 92px);
    box-sizing: border-box;
    padding: 12px;

    .order-create-form-container {
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      padding: 12px;
      background-color: #fff;
      height: 100%;
    }

    .header {
      width: 100%;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      background-color: #fff;
      align-items: center;
      padding: 0 12px;

      .title {
        font-size: 14px;
        color: #383838;
      }

      .btn_group {
        display: flex;
        gap: 5px;
      }
    }

    .divider {
      border-bottom: 1px dotted #d4d4d4;
      margin: 12px 0;
    }

    .all_form_container {
      flex: 1;
      height: 0;
      width: 100%;
      overflow: auto;
      display: flex;
      flex-direction: column;
      row-gap: 32px;

      .order_info {
        display: flex;
        flex-direction: column;
        background-color: #fff;
        padding: 0 12px;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }

        :deep(.el-form) {
          display: grid;
          grid-template-columns: repeat(3, minmax(200px, 1fr));
          column-gap: 100px;
          margin-top: 18px;
          row-gap: 18px;
          padding: 0 38px;

          .el-form-item {
            margin: 0;

            .el-form-item__label {
              height: 16px;
              line-height: 16px;
              margin: 0 0 3px 0;
            }

            .el-form-item__content {
              width: 100%;
              align-items: flex-start;

              .fault-desc-container {
                width: 100%;
                display: flex;
                flex-direction: column;
                row-gap: 8px;

                .quick-item-list {
                  display: flex;
                  flex-wrap: wrap;
                  column-gap: 8px;
                  row-gap: 4px;

                  .quick-item {
                    width: fit-content;
                    height: 24px;
                    border-radius: 24px;
                    border: 1px solid #eee;
                    padding: 0 8px;
                    line-height: 24px;
                    cursor: pointer;
                  }
                }
              }

              .el-select {
                max-width: unset;
                width: 100%;
              }

              .el-input {
                width: 100%;
                max-width: unset;
                height: 28px;

                .el-input__wrapper {
                  height: 26px;
                }
              }

              .el-form-item__error {
                margin: 0;
                padding-top: 4px;
              }

              .el-textarea {
                .el-textarea__inner {
                  width: 100% !important;
                  max-height: 200px !important;
                  min-height: 28px !important;
                  height: 28px;
                }
              }

              .desc-28-height {
                .el-textarea__inner {
                  max-height: 100px !important;
                  min-height: 28px !important;
                }
              }

              .desc-75-height {
                .el-textarea__inner {
                  max-height: 285px !important;
                  min-height: 75px !important;
                }
              }

              .upload_file_container {
                width: 100% !important;
                display: flex;
                flex-wrap: wrap;
                gap: 5px;

                .order-picture-upload {
                  width: 80px;
                  height: 50px;

                  .el-upload {
                    width: 100%;
                    height: 100%;

                    .el-upload-dragger {
                      display: flex;
                      align-items: center;
                      column-gap: 5px;
                      width: 100%;
                      height: 100%;
                      padding: 0;
                      background: none;
                      justify-content: center;
                    }
                  }
                }

                .file_list {
                  display: grid;
                  grid-template-columns: repeat(2, 1fr);
                  margin-top: 5px;
                  width: 100%;
                  row-gap: 5px;
                  column-gap: 12px;

                  .file_item {
                    flex: 1;
                    list-style: none;
                    display: flex;
                    column-gap: 5px;
                    height: 16px;
                    align-items: center;

                    .file_name {
                      width: 100%;
                      line-height: 14px;
                      text-overflow: ellipsis;
                      white-space: nowrap;
                      overflow: hidden;
                      text-align: center;
                      margin-top: 2px;
                    }
                  }
                }
              }
            }
          }
        }
      }

      .custom_info {
        background-color: #fff;
        display: flex;
        flex-direction: column;
        padding: 0 12px;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }

        .form-content {
          display: grid;
          grid-template-columns: repeat(2, 440px);
          column-gap: 100px;
          margin-top: 18px;
          row-gap: 18px;
          padding: 0 38px;

          :deep(.el-form) {
            .el-form-item {
              width: 100%;
              margin: 0;

              .el-form-item__label {
                height: 16px;
                line-height: 16px;
                margin: 0 0 3px 0;
              }

              .el-form-item__content {
                .el-form-item__error {
                  margin: 3px 0 0 0;
                  padding: 0;
                }

                .el-rate {
                  height: 28px;
                }

                .el-select {
                  width: 100% !important;
                }

                .el-date-editor {
                  height: 28px;
                  width: 100%;

                  .el-input__wrapper {
                    height: 26px;
                  }
                }

                .custom-field-upload {
                  display: flex;
                  gap: 5px;
                  flex-wrap: wrap;

                  .upload-wrapper {
                    width: 80px;
                    height: 50px;

                    .el-upload {
                      width: 100%;
                      height: 100%;
                      display: flex;
                      justify-content: center;
                      padding: 0;
                      box-shadow: 0 0 0 1px #dcdfe6 inset;
                      box-sizing: border-box;

                      .text {
                        line-height: 16px;
                        height: 16px;
                        color: #999;
                      }
                    }
                  }
                }

                .el-textarea {
                  height: 100%;
                  width: 100%;

                  .el-textarea__inner {
                    width: 100% !important;
                    min-height: 75px !important;
                    max-height: 140px !important;
                  }
                }
              }
            }
          }
        }
      }

      .customer_info {
        background-color: #fff;
        box-sizing: border-box;
        padding: 0 12px;

        .title {
          font-size: 14px;
          padding-left: 6px;
          border-left: 3px solid $primaryColor;
          font-weight: bold;
        }

        .form_content {
          display: grid;
          grid-template-columns: repeat(3, minmax(200px, 1fr));
          column-gap: 100px;
          margin-top: 18px;
          row-gap: 18px;
          padding: 0 38px;

          :deep(.el-form-item) {
            margin: 0 !important;

            .el-form-item__label {
              height: 16px;
              line-height: 16px;
              margin: 0 0 3px 0;
            }

            .el-form-item__content {
              width: 100% !important;
              flex-direction: column;
              align-items: flex-start;

              .el-select {
                width: 100% !important;
                max-width: unset !important;
              }

              .detail_address {
                .el-textarea__inner {
                  width: 100% !important;
                  height: 28px;
                  min-height: 28px !important;
                  max-height: 155px !important;
                }
              }

              .address_identify {
                display: flex;
                gap: 12px;
                align-items: center;
                width: 100%;
              }

              .el-textarea {
                .el-textarea__inner {
                  width: 100% !important;
                  max-height: 200px !important;
                  min-height: 28px !important;
                  height: 28px;
                }
              }

              .el-form-item__error {
                margin: 0;
                padding-top: 4px;
              }
            }
          }
        }
      }

      .good-info {
        // flex: 1;
      }
    }

    // 公司信息
    .customer_info_form_content {
      background-color: #fff;
      box-sizing: border-box;
      padding: 12px;
      margin-top: 12px;

      :deep(.el-form-item) {
        margin-bottom: 15px;
      }

      .title {
        font-size: 14px;
        border-left: 3px solid $primaryColor;
        color: #383838;
        padding-left: 6px;
      }

      .userinfo {
        display: flex;
        gap: 60px;

        .address_identify {
          .address_identify_content {
            display: flex;
            gap: 10px;

            .textarea {
              width: 300px;
            }

            .btn {
              padding: 0 10px;
              border-color: rgba($primaryColor, 0.8);
              color: rgba($primaryColor, 0.8);
              // border-radius: 4px;

              &:hover {
                border-color: $primaryColor;
                color: #fff;
                background-color: $primaryColor;
              }
            }
          }
        }

        .customer_name,
        .customer_phone {
          width: 240px;
        }

        .detail_address,
        .customer_address {
          width: 100%;
        }

        :deep(.el-form-item__content) {
          max-width: 700px;
        }
      }
    }
  }

  .pic {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    // margin-left: 4px;
  }

  :deep(.el-form-item--default) {
    --font-size: 12px;
  }

  .app-container {
    padding: 0 12px;
    padding-top: 10px;
  }

  .mar_r {
    margin-top: 10px;
    margin-right: 20px;
  }

  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-main) {
    --el-main-padding: 0;
  }

  :deep(.code-dialog) {
    height: 100%;

    .el-dialog__body {
      padding: 0;
    }

    .header {
      display: flex;
      justify-content: flex-end;

      .w120 {
        width: 120px;
        margin-right: 5px;
      }

      .el-date-editor {
        width: 250px;
        margin-right: 10px;
      }

      .input-with-select {
        width: 180px;
        margin-right: 8px;
      }

      .mr_5 {
        margin-right: 5px;
      }

      .el-button + .el-button {
        margin-left: 8px;
      }

      .input-with-select_w {
        width: 250px;
        margin-left: 8px;
      }

      .w100 {
        width: 100px;
      }
    }

    .el-dialog__footer {
      border-top: 1px solid #e4e7ed;
      padding: 10px 20px;
    }

    .table-reg {
      width: 100%;
      margin: 10px 0;
      height: 486px;
    }

    .footer {
      padding: 10px 0;
      position: absolute;
      margin-bottom: 0;
      bottom: 0;
      z-index: 999;
    }
  }

  :deep(.demo-tabs) {
    .el-table {
      .cell {
        // text-align: center;
        font-size: 12px;
      }

      th.el-table__cell + th.el-table__cell {
        .cell {
          border-left: 1px solid #e7e3e3;
        }
      }
    }

    .el-table--border .el-table__cell {
      border-right: none;
    }

    .el-tabs__header {
      margin: 0;
    }

    .el-tabs__item {
      margin: 0 20px;
    }

    .el-tabs__nav-wrap::after {
      height: 1px;
    }

    .el-tabs__nav .el-tabs__active-bar {
      padding: 0 10px;
      position: absolute;
      bottom: 0;
      left: -10px;
    }

    .main_left {
      border: 1px solid #e4e7ed;
      border-bottom: none;
      border-radius: 2px;
      position: relative;
      height: calc(100% - 1px);

      .titile_h4 {
        border-bottom: 1px solid #e4e7ed;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
      }

      .ul_pop_up {
        padding: 0 30px 30px;

        .li_pop_up {
          padding: 5px 0;
          cursor: pointer;
          font-size: 12px;

          &:hover {
            color: #999;
          }
        }
      }

      .page_pages {
        width: 100%;
        overflow-x: auto;
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        bottom: 0;
      }

      .btn_save {
        width: 50px;
        height: 30px;
        border-radius: 2px;
      }

      .btn_cancel {
        width: 50px;
        height: 30px;
        border-radius: 2px;

        &:hover {
          border: 1px solid #e5e5e5;
          color: #999;
          background-color: #e5e5e5;
        }
      }
    }

    .main_right {
      padding: 12px 20px;
      height: calc(100% - 24px);
    }

    .table-user {
      margin: 10px 20px;
      height: 500px;
    }
  }

  .userinfo_select_empty {
    display: flex;
    justify-content: center;
  }

  .create-user-btn {
    width: -webkit-fill-available !important;
  }
</style>
<style lang="scss">
  .el-popover.monitor-yt-popover {
    padding: 6px 0;

    .user_item {
      font-size: 12px;
      margin: 0 12px;
      padding: 8px 12px;
      cursor: pointer;
      display: flex;
      align-items: center;
      flex-wrap: nowrap;

      &:hover {
        background-color: rgb(245, 247, 250);
      }
    }
  }
</style>
